package fr.mma.livraison;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

import fr.mma.livraison.controller.Factory;
import fr.mma.livraison.controller.DevController;
import fr.mma.livraison.model.dto.DeveloppeurDTO;
import fr.mma.livraison.model.dto.reponse.ReponseDTO;
import fr.mma.livraison.model.dto.reponse.ReponseKO;
import fr.mma.livraison.model.dto.reponse.ReponseOK;
import fr.mma.livraison.model.persistence.Developpeur;

public class DevServlet extends AbstractServlet<DeveloppeurDTO> {
	/** */
	private static final long serialVersionUID = 6288202946451485676L;

	public void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
		resp.setContentType("application/json");
		final DevController mainController = new DevController();
		final Developpeur dev = mainController.getDevByTrigram(req.getParameter("name"));
		final Gson gson = new Gson();
		final String json = gson.toJson(Factory.build(dev));
		resp.getWriter().println(json);
	}

	@Override
	protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
		final Gson gson = new Gson();
		if (isAdmin(req)) {
			final DeveloppeurDTO request = gson.fromJson(req.getParameter("request"), DeveloppeurDTO.class);
			final DevController mainController = new DevController();
			mainController.save(request);
			resp.setContentType("application/json");
			resp.getWriter().println(gson.toJson("ok"));
		} else {
			resp.getWriter().println(gson.toJson("ko"));
		}

	}

	@Override
	protected ReponseDTO postDTO(final DeveloppeurDTO dto, final String userName) {
		ReponseDTO reponse = new ReponseKO("Pas les droits");
		if (dao.isAdmin(userName)) {
			final DevController mainController = new DevController();
			mainController.save(dto);
			reponse = new ReponseOK();
		}
		return reponse;
	}

	@Override
	protected void postEmpty(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
		// RAS
	}

	@Override
	protected Class<DeveloppeurDTO> getDTOClass() {
		return DeveloppeurDTO.class;
	}
}
